package com.rs.caht.netty.chatdemo.server;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.util.concurrent.GlobalEventExecutor;

//自定义一个服务器端业务处理类

/***
 * 处理消息的handler
 * TextWebSocketFrame: 在netty中，是用于为websocket专门处理文本的对象，frame是消息的载体
 */
public class ChatServerHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {
    // 用来保存所有的客户端连接
    public static ChannelGroup channelsClient = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);

    @Override  //通道就绪
    public void channelActive(ChannelHandlerContext ctx) {
        Channel inChannel = ctx.channel();
        channelsClient.add(ctx.channel());
        System.out.println("[Server-channelActive通道就绪]:" + inChannel.remoteAddress().toString().substring(1) + "上线");
    }

    @Override  //通道未就绪
    public void channelInactive(ChannelHandlerContext ctx) {
        Channel inChannel = ctx.channel();
        channelsClient.remove(inChannel);
        System.out.println("[Server-channelInactive通道未就绪]:" + inChannel.remoteAddress().toString().substring(1) + "离线");
    }

    @Override  //读取数据
    protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame s) {
        String msg = s.text();
        System.out.println("server收到消息:" + msg);
        Channel inChannel = ctx.channel();
        for (Channel channel : channelsClient) {
            if (channel != inChannel) {
                System.out.println("发给除自己外的其他人");
                channel.writeAndFlush(new TextWebSocketFrame("[Server-channelRead0-读取数据" + inChannel.remoteAddress().toString().substring(1) + "]" + "说：" + msg + "\n"));
            }
        }
        System.out.println("给自己的回执");
        inChannel.writeAndFlush(new TextWebSocketFrame("[Server-channelRead0-读取数据" + inChannel.remoteAddress().toString().substring(1) + "]" + "说：" + "服务器已经收到消息" + "\n"));
    }

    // 当有新的客户端连接服务器之后，会自动调用这个方法
    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
        // 将新的通道加入到clients
        System.out.println("有新的客户端连接服务器");

    }

    //异常调用
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
//        UserChannelMap.removeByChannelId(ctx.channel().id().asLongText());
        System.out.println("异常关闭通道");
        ctx.channel().close();
    }

    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
        System.out.println("关闭通道");
//        UserChannelMap.removeByChannelId(ctx.channel().id().asLongText());
//        UserChannelMap.print();
    }

}
